package com.bwie.controller;

import com.alibaba.fastjson.JSONObject;
import com.bwie.feign.UserFeign;
import com.bwie.pojo.User;
import com.bwie.pojo.resp.JwtResponse;
import com.bwie.result.Result;
import com.bwie.utils.JwtUtils;
import com.bwie.utils.StringUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping
@Log4j2
public class AuthController {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @PostMapping("/login")
    public Result<JwtResponse> login(@RequestBody User user){
        log.info("功能名称:鉴权登录,请求路径:{},请求路径:{},请求参数:{}",request.getRequestURI(),
                request.getMethod(), JSONObject.toJSONString(user));
        //判断不能为空
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())){
            Result<JwtResponse> result = Result.error("账号或密码不能为空");
            return result;
        }
        Result<User> byUsername = userFeign.findByUsername(user.getUsername());
        User userLogin = byUsername.getData();
        if (userLogin==null){
            Result<JwtResponse> result = Result.error("账号不存在");
            return result;
        }
        if (!user.getPassword().equals(userLogin.getPassword())){
            Result<JwtResponse> result = Result.error("密码错误");
            return result;
        }
        //生成token
        String userKey = UUID.randomUUID().toString().replaceAll("-", "");
        HashMap<String, Object> jwtMap = new HashMap<>();
        jwtMap.put(JwtUtils.DETAILS_USER_ID,userLogin.getId());
        jwtMap.put(JwtUtils.USER_KEY,userKey);
        redisTemplate.opsForValue().set(JwtUtils.LOGIN_TOKEN_KEY+userKey,JSONObject.toJSONString(userLogin),30, TimeUnit.MINUTES);
        String token = JwtUtils.createToken(jwtMap);
        JwtResponse jwtResponse = new JwtResponse();
        jwtResponse.setToken(token);
        jwtResponse.setExpireTime("30MIN");
        Result<JwtResponse> result = Result.success(jwtResponse);
        return result;
    }

    //用户信息
    @GetMapping("/user/info")
    public Result<User> getUserInfo(){
        String token = request.getHeader(JwtUtils.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        String userJson = redisTemplate.opsForValue().get(JwtUtils.LOGIN_TOKEN_KEY + userKey);
        User user = JSONObject.parseObject(userJson, User.class);
        redisTemplate.opsForValue().set("user",JSONObject.toJSONString(user));
        Result<User> result = Result.success(user);
        return result;
    }
}
